package com.lishem.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.lishem.utils.ByteBufferUtil.debugAll;

@Slf4j
public class AioFileChannel {
    public static void main(String[] args) {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("helloword/data.txt"), StandardOpenOption.READ)) {
            // 参数1  ByteBuffer
            // 参数2  读取的起始位置
            // 参数3  附件
            // 参数4  回调对象
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override // read 成功
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed..{}",result);
                    attachment.flip();
                    debugAll(attachment);
                }

                @Override // read失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 因为异步IO返回结果的是守护线程，主线程现在还不能结束
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/*
16:11:12 [DEBUG] [main] c.i.n.c.AioFileChannel - read begin
16:11:12 [DEBUG] [main] c.i.n.c.AioFileChannel - read end...
16:11:12 [DEBUG] [Thread-12] c.i.n.c.AioFileChannel - read completed..13
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [13]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 31 32 33 34 35 36 37 38 39 30 61 62 63 00 00 00 |1234567890abc...|
+--------+-------------------------------------------------+----------------+
*/